package com.teziyou.commodity.core.thrift;

import org.apache.commons.pool2.BasePooledObjectFactory;
import org.apache.commons.pool2.PooledObject;
import org.apache.commons.pool2.impl.DefaultPooledObject;
import org.apache.thrift.transport.TFramedTransport;
import org.apache.thrift.transport.TSocket;
import org.apache.thrift.transport.TTransport;

import com.teziyou.commodity.constant.Global;

public class ThriftPoolableObjectFactory extends BasePooledObjectFactory<TTransport> {

	/** 服务的IP */
	private String ip;
	/** 服务的端口 */
	private int port;
	/** 超时设置 */
	private int timeout;
	
	private int type;
	
	public ThriftPoolableObjectFactory(String ip, int port, int timeout, int type) {
		super();
		this.ip = ip;
		this.port = port;
		this.timeout = timeout;
		this.type = type;
	}

	@Override
	public TTransport create() throws Exception {
		//System.err.println("创建");
		try {
			//TTransport transport = new TFramedTransport(new TSocket(ip, port, timeout));
			TTransport transport = null;
			//System.err.println(ip);
			if(type==Global.TTransportType.common) {
				transport = new TSocket(ip, port, timeout);
			} else if(type==Global.TTransportType.nio) {
				System.err.println("framed");
				transport = new TFramedTransport(new TSocket(ip, port, timeout));
			}
			transport.open();
			return transport;
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	@Override
	public PooledObject<TTransport> wrap(TTransport obj) {
		return new DefaultPooledObject<TTransport>(obj);
	}

	@Override
	public void destroyObject(PooledObject<TTransport> p) throws Exception {
		if(p.getObject().isOpen()) {
			//System.err.println("销毁");
			p.getObject().close();
		}
	}

	@Override
	public boolean validateObject(PooledObject<TTransport> p) {
		//System.err.println("验证");
		return p.getObject().isOpen();
	}

	@Override
	public void activateObject(PooledObject<TTransport> p) throws Exception {
		//System.err.println("激活");
		super.activateObject(p);
	}

	@Override
	public void passivateObject(PooledObject<TTransport> p) throws Exception {
		//System.err.println("passivate");
		super.passivateObject(p);
	}

	public String getIp() {
		return ip;
	}
	public void setIp(String ip) {
		this.ip = ip;
	}
	public int getPort() {
		return port;
	}
	public void setPort(int port) {
		this.port = port;
	}
	public int getTimeout() {
		return timeout;
	}
	public void setTimeout(int timeout) {
		this.timeout = timeout;
	}
	public int getType() {
		return type;
	}
	public void setType(int type) {
		this.type = type;
	}

}
